// components/learning/learning.js
const app = getApp()
let innerAudioContext = null
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    show: {
      type: Boolean,
      value: false,
      observer: function(show){
        if (show) {
        } else {
          clearInterval(this.data.intervalId)
          this.setData({
            showText: [],
            intervalId: ''
          })
        }
      }
    },
    sceneId: {
      type: String,
      observer: function(newVal, oldVal){
        this.getDialogs()
      }
    },
    trainSceneId: {
      type: String,
      value: ''
    },
    levelId: {
      type: String,
      value: ''
    },
    recordType: {
      type: String,
      value: ''
    },
    playingIdx: {
      type: Number,
      observer: function(playingIdx, oldVal){
        this.playTarget(playingIdx)
      }
    },
    customerSex: {
      type: String,
      value: 'female'
    },
    from: {
      type: String,
      value: ''
    },
    isRecommended: {
      type: String,
      value: 'N'
    }
  },
  options: {
    addGlobalClass: true,
  },

  /**
   * 组件的初始数据
   */
  data: {
    hasTrainPower:false,
    CDNPATH: app.globalData.CDNPATH,
    imgResUrl: '',
    list: [],
    showText: [],
    scrollTop: 0,
    isPlaying: false,
    waitingVoice: false, // 等待url，开始或已播完但下一个url还未返回
    rates: [1.0, 1.25, 1.5, 2.0],
    speedIndex: 0,
    isIOS: false,
    getEnergyShow: false
  },
  created () {
    wx.getSystemInfo({
      success: (res) => {
        if (res.system.indexOf('iOS') > -1) {
          this.setData({ isIOS: true })
        }
      }
    })
    // 播放监听避免重复绑定
    innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.playbackRate = 1
    innerAudioContext.autoplay = false // 倍速隐藏
    innerAudioContext.onCanplay(() => {
      console.log('can play')
    })
    innerAudioContext.onPlay(() => {
      console.log('开始播放')
      this.setData({
        isPlaying: true
      })
    })
    innerAudioContext.onEnded(() => {
      let { playingIdx, isPlaying } = this.data
      console.log('ended', isPlaying)
      playingIdx++
      this.setData({
        isPlaying: false
      })
      this.playTarget(playingIdx,true)
    })
    innerAudioContext.onPause(() => {
      console.log('pause')
      this.setData({
        isPlaying: false
      })
    })
    innerAudioContext.onStop(() => {
      console.log('stop')
      this.setData({
        isPlaying: false
      })
    })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
      
    })
    
  },
  ready: function () {
    console.log(this.data.CDNPATH)
    this.setData({
      imgResUrl: app.globalData.userInfo.imgResUrl
    })
    const permissionCodes = app.globalData.permissionCodes || []
    console.log(permissionCodes,'permissionCodes');
    const hasPower = permissionCodes.includes('rehearse')
    console.log(hasPower,'hasPower');
    this.setData({
      hasTrainPower:hasPower
    })
    // wx.setInnerAudioOption({
    //   obeyMuteSwitch: false
    // })
  },
  detached () {
    console.log('detached')
    this.destroyAudio()
  },
  pageLifetimes: {
    hide () {
      console.log('hide')
      innerAudioContext.pause()
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    getDialogs () {
      const {sceneId,trainSceneId,recordType,isRecommended,levelId} = this.data
      console.log('trainSceneId,recordType',trainSceneId,recordType,isRecommended)
      app.api.post({
        // 根据场景id查询场景对话信息
        url: 'scene_manage_get_nodes',
        data: {
          sceneId,
          trainSceneId:trainSceneId!=='undefined'?trainSceneId:'',
          levelId: levelId!=='undefined'?levelId:'',
          recordSave:true,
          recordType,
          isRecommended
        }
      }).then(res => {
        let list = []
        if (res.sceneType === 'knowledge_question') {
          // 知识问答,机器人先说
          res.sceneNodeInfos.map(({replyScript, highlightStandardScript, id}) => {
            list.push({role: 'robot', word: replyScript, id}, {role: 'customer', word: highlightStandardScript, id})
          })
        } else {
          // 流程话术,客户先说
          res.sceneNodeInfos.map(({replyScript, highlightStandardScript, id}) => {
            list.push({role: 'customer', word: highlightStandardScript, id}, {role: 'robot', word: replyScript, id})
          })
        }
        this.setData({
          list: list,
          totalRound: res.totalRound
        })
        list.forEach((item, index) => {
          this.getVideo(item, index)
        })
        this.triggerEvent('changeTotal', { totalRound: res.totalRound }, {})
      })
    },
    getVideo (item, index) {
      const { sceneId } = this.data
      let roleType, gender
      if (item.role === 'customer') {
        roleType = 'trainee'
        gender = 'female'
      } else {
        roleType = 'robot'
        gender = this.data.customerSex
      }
      app.api.post({
        url: 'scene_manage_message2voice',
        data: {
          scriptNodeId: item.id,
          roleType,
          gender,
          sceneId
        }
      }).then(res => {
        const { isPlaying, waitingVoice, playingIdx } = this.data
        this.setData({
          [`list[${index}].voicePath`]: res.scriptWavVoicePath,
        })
        if (index === 0) {
          // 第一句返回设置src但不播放
          innerAudioContext.src = res.scriptWavVoicePath
        }
        if (waitingVoice && playingIdx === index) {
          // 等待中的返回了就播放
          innerAudioContext.src = res.scriptWavVoicePath
          innerAudioContext.play()
        }
      }, () => {
        this.setData({
          [`list[${index}].voicePath`]: null,
        })
      })
    },
    // speed () {
    //   let { speedIndex, isIOS } = this.data
    //   const { playingIdx, list } = this.data
    //   speedIndex < 3 ? speedIndex++ : speedIndex = 0
    //   this.setData({
    //     speedIndex 
    //   })
    //   // 播放到最后，倍速不设置(设置会重新播放)，在拖动slider时playTarget设置
    //   if (playingIdx > list.length - 1) {
    //     return
    //   }
    //   if (isIOS) {
    //     // 安卓和ios倍速播放表现不一致
    //     this.iosSpeed()
    //   } else {
    //     this.androidSpeed()
    //   }
    // },
    // androidSpeed () {
    //   // 安卓autoplay时，设置倍速会马上生效,否则要到下一句才生效,若先暂停再播放，可能会有2个同时播放
    //   const { isPlaying, rates, speedIndex } = this.data
    //   const speedRate = rates[speedIndex]
    //   if (!isPlaying) {
    //     innerAudioContext.play()
    //   }
    //   wx.nextTick(() => {
    //     innerAudioContext.playbackRate = speedRate
    //   })
    // },
    // iosSpeed(){
    //   // ios设置倍速不会马上生效，要先暂停再播放
    //   const { isPlaying, rates, speedIndex } = this.data
    //   const speedRate = rates[speedIndex]
    //   innerAudioContext.playbackRate = speedRate
    //   innerAudioContext.pause()
    //   if (isPlaying) {
    //     innerAudioContext.play();
    //   }
    // },
    close () {
      this.triggerEvent('close', {}, {})
      innerAudioContext.pause()
      innerAudioContext = null
    },
    playTarget (index,status) {
      const { list, rates, speedIndex, isPlaying } = this.data
      if (index > list.length - 1) {
        innerAudioContext.stop()
        this.triggerEvent('setPlayIdx', { index }, {})
        if (status) {
          this.getSceneStudyEnergy()
        }
        return
      }
      const src = list[index].voicePath
      if (src === null) {
        // 音频地址返回错误
        wx.showToast({
          title: '音频获取失败，可暂停进行学习',
          icon: 'none',
          duration: 2000
        })
        return
      } else if (src) {
        this.setData({ playingIdx: index })
        innerAudioContext.stop()
        console.log(index)
        wx.nextTick(() => {
          innerAudioContext.src = list[index].voicePath
          innerAudioContext.play()
        })
        // 倍速隐藏，先注释
        // innerAudioContext.src = list[index].voicePath
        // innerAudioContext.play()
        // wx.nextTick(() => {
        //   innerAudioContext.playbackRate = rates[speedIndex]
        // })
      } else {
        this.setData({
          waitingVoice: true,
          playingIdx: index
        })
      }
      this.triggerEvent('setPlayIdx', { index }, {})
    },
    handlePlay () {
      // 点击播放暂停
      const { isPlaying, playingIdx, list } = this.data
      if (playingIdx > list.length - 1) {
        wx.showToast({
          title: '恭喜您，您已经学完啦',
          icon: 'none',
          duration: 2000
        })
      } else {
        this.setData({
          isPlaying: !isPlaying
        })
        if (innerAudioContext.src) {
          console.log('11111111==============');
          console.log('11111111==============!!!!!!!!',isPlaying);
          isPlaying ? innerAudioContext.pause() : innerAudioContext.play()
        } else {
          this.setData({
            waitingVoice: !isPlaying,
          })
        }
      }
    },
    destroyAudio () {
      if (innerAudioContext) {
        innerAudioContext.stop()
        innerAudioContext.destroy()
      }
    },
    getSceneStudyEnergy () {
      console.log(this.data.from)
      if (this.data.from!=='mytrain') {
        app.api.get({
          url: 'getSceneStudyEnergy',
          data: { sceneId: this.data.sceneId },
        }).then(res => {
          if(res.data > 0){
            this.setData({
              getEnergyShow:true,
              signEnergyCount: res.data
            })
          }
        })
      }
    },
    closeEnergyShow () {
      console.log(2222)
      this.setData({
        getEnergyShow:false
      })
    },
  }
})
